"use client"

import { useState, useEffect, useRef, useCallback } from "react"
import type { Player, PlayerCategory } from "@/lib/types"
import { getRankings } from "@/lib/data"
import PlayerRow from "./player-row"
import TierView from "./tier-view"
import { getTitleByScore } from "@/lib/utils"
import { ArrowUp, Trophy, Info } from "lucide-react"

// 将类别映射到API游戏模式
const categoryToMode: Record<string, string | undefined> = {
  "overall": undefined,
  "combat": "SWORD",
  "crystal": "CRYSTAL",
  "heart": "BUHC",
  "potion": "POTION", 
  "discord": "NPOT",
  "circle": "SMP"
};

// 将类别映射到段位属性
const categoryToTierProp: Record<string, string> = {
  "combat": "swordTier",
  "crystal": "crystalTier",
  "heart": "buhcTier",
  "potion": "potionTier", 
  "discord": "npotTier",
  "circle": "smpTier"
};

interface PlayerRankingsProps {
  category: PlayerCategory
}

export interface RankingPlayer {
  id: number;
  name: string;
  avatar: string;
  region: string;
  score: number;
  tier?: number | null;
  tierName?: string;
  swordTier?: number | null;
  crystalTier?: number | null;
  buhcTier?: number | null;
  potionTier?: number | null;
  npotTier?: number | null;
  smpTier?: number | null;
  // 段位名称
  swordTierName?: string;
  crystalTierName?: string;
  buhcTierName?: string;
  potionTierName?: string;
  npotTierName?: string;
  smpTierName?: string;
  // 最高段位信息
  bestTier?: number | null;
  bestTierName?: string;
  bestTierMode?: string;
}

export default function PlayerRankings({ category }: PlayerRankingsProps) {
  const [allPlayers, setAllPlayers] = useState<Player[]>([])
  const [displayPlayers, setDisplayPlayers] = useState<Player[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [loadingMore, setLoadingMore] = useState(false)
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  const loaderRef = useRef<HTMLDivElement>(null)
  const PLAYERS_PER_PAGE = 10
  const [showScrollTop, setShowScrollTop] = useState(false)

  // 用于观察滚动到底部的函数
  const observer = useRef<IntersectionObserver | null>(null)
  const lastPlayerElementRef = useCallback((node: HTMLDivElement | null) => {
    if (loadingMore) return
    if (observer.current) observer.current.disconnect()
    observer.current = new IntersectionObserver(entries => {
      if (entries[0].isIntersecting && hasMore) {
        loadMorePlayers()
      }
    })
    if (node) observer.current.observe(node)
  }, [loadingMore, hasMore])

  // 检测滚动位置以显示/隐藏回到顶部按钮
  useEffect(() => {
    const handleScroll = () => {
      setShowScrollTop(window.scrollY > 300)
    }
    
    window.addEventListener('scroll', handleScroll)
    return () => window.removeEventListener('scroll', handleScroll)
  }, [])

  // 回到顶部功能
  const scrollToTop = () => {
    window.scrollTo({
      top: 0,
      behavior: 'smooth'
    })
  }

  // 初始数据加载
  useEffect(() => {
    const loadPlayers = async () => {
      setIsLoading(true)
      setPage(1)
      
      try {
        // 获取对应模式的排名数据
        const mode = categoryToMode[category]
        const rankingData = await getRankings(mode)
        
        // 如果是特定模式，还需要获取总排行榜数据
        let overallRankings: any[] = []
        if (category !== "overall") {
          overallRankings = await getRankings()
        }
        
        console.log("API返回的原始数据:", rankingData)
        
        // 转换为 Player 类型
        const formattedPlayers = rankingData.map((player: RankingPlayer, index: number) => {
          // 确定显示哪个段位
          let tierValue: number | null = null;
          let tierName: string = '';  // 段位名称
          let tierMode: string = '';  // 段位对应的游戏模式
          
          if (category === "overall") {
            // 总排行使用API返回的最高段位
            tierValue = player.bestTier || null;
            tierName = player.bestTierName || '';
            tierMode = player.bestTierMode || '';
          } else {
            // 特定模式下，直接使用API返回的tier值
            tierValue = player.tier !== undefined && player.tier !== null 
              ? Number(player.tier) 
              : null;
            tierName = player.tierName || '';
            tierMode = mode || '';
          }
          
          // 获取玩家称号信息
          const titleInfo = getTitleByScore(player.score || 0);
          
          // 创建玩家数据对象
          let playerData: any = {
            ...player,
            id: player.id.toString(),
            title: { 
              name: titleInfo.name, 
              color: titleInfo.color, 
              points: player.score || 0,
              icon: titleInfo.icon,
              description: titleInfo.description
            },
            avatar: player.avatar || "/placeholder-user.jpg",
            rank: index + 1, // 当前模式下的排名
            tier: tierValue,
            tierName: tierName,
            tierMode: tierMode,
          };
          
          // 如果是特定模式，查找该玩家在总排行榜中的数据
          if (category !== "overall" && overallRankings.length > 0) {
            // 在总排行榜中查找该玩家
            const overallData = overallRankings.find(p => p.id.toString() === player.id.toString());
            
            if (overallData) {
              // 保存总排行榜中的排名和分数
              playerData.overallRank = overallRankings.indexOf(overallData) + 1;
              playerData.overallScore = overallData.score;
              
              // 使用总排行榜的分数重新计算称号
              const updatedTitleInfo = getTitleByScore(overallData.score || 0);
              playerData.title = {
                name: updatedTitleInfo.name,
                color: updatedTitleInfo.color,
                points: overallData.score || 0,
                icon: updatedTitleInfo.icon,
                description: updatedTitleInfo.description
              };
              
              // 保存所有模式的tier信息
              playerData.swordTier = overallData.swordTier;
              playerData.crystalTier = overallData.crystalTier;
              playerData.buhcTier = overallData.buhcTier;
              playerData.potionTier = overallData.potionTier;
              playerData.npotTier = overallData.npotTier;
              playerData.smpTier = overallData.smpTier;
              
              // 保存所有模式的tier名称
              playerData.swordTierName = overallData.swordTierName;
              playerData.crystalTierName = overallData.crystalTierName;
              playerData.buhcTierName = overallData.buhcTierName;
              playerData.potionTierName = overallData.potionTierName;
              playerData.npotTierName = overallData.npotTierName;
              playerData.smpTierName = overallData.smpTierName;
              
              // 保存最佳tier信息
              playerData.bestTier = overallData.bestTier;
              playerData.bestTierName = overallData.bestTierName;
              playerData.bestTierMode = overallData.bestTierMode;
            }
          }
          
          // 添加其他标准字段
          playerData.skills = [];
          playerData.playTime = 0;
          playerData.currentTiers = [];
          playerData.retiredTiers = [];
          
          return playerData;
        });
        
        console.log("转换后的玩家数据:", formattedPlayers);
        
        setAllPlayers(formattedPlayers);
        setDisplayPlayers(formattedPlayers.slice(0, PLAYERS_PER_PAGE));
        setHasMore(formattedPlayers.length > PLAYERS_PER_PAGE);
      } catch (error) {
        console.error("Failed to load rankings:", error);
        setAllPlayers([]);
        setDisplayPlayers([]);
        setHasMore(false);
      } finally {
        setIsLoading(false);
      }
    };
    
    loadPlayers();
  }, [category]);

  // 加载更多玩家函数
  const loadMorePlayers = () => {
    if (!hasMore || loadingMore) return
    
    setLoadingMore(true)
    
    setTimeout(() => {
      const nextPage = page + 1
      const startIndex = (nextPage - 1) * PLAYERS_PER_PAGE
      const endIndex = nextPage * PLAYERS_PER_PAGE
      
      setDisplayPlayers(prev => [...prev, ...allPlayers.slice(startIndex, endIndex)])
      setPage(nextPage)
      setHasMore(endIndex < allPlayers.length)
      setLoadingMore(false)
    }, 500) // 模拟网络延迟
  }

  if (isLoading) {
    return (
      <div className="flex flex-col items-center justify-center py-12 animate-pulse">
        <div className="w-12 h-12 border-4 border-blue-500 border-t-transparent rounded-full animate-spin mb-4"></div>
        <div className="text-center text-gray-400">加载中...</div>
      </div>
    );
  }

  return (
    <div className="space-y-4 animate-fade-in relative">
      {/* 回到顶部按钮 */}
      {showScrollTop && (
        <button 
          onClick={scrollToTop}
          className="scroll-top-btn"
          aria-label="回到顶部"
        >
          <ArrowUp className="h-5 w-5" />
        </button>
      )}
      
      {/* 页面顶部装饰元素 */}
      <div className="absolute top-0 right-0 w-48 h-48 bg-blue-500/5 rounded-full blur-3xl -z-10 transform translate-x-1/3 -translate-y-1/3"></div>
      <div className="absolute top-1/4 left-0 w-32 h-32 bg-purple-500/5 rounded-full blur-2xl -z-10 transform -translate-x-1/3"></div>
      
      {/* 标题和信息提示 */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-2">
          <h2 className="text-xl font-bold text-white hidden sm:block">
            {getCategoryName(category)}排行榜
          </h2>
          {category === 'overall' && (
            <div className="hidden sm:flex items-center bg-[#323842] text-xs text-gray-400 px-2 py-1 rounded-md">
              <Info className="h-3 w-3 mr-1" />
              <span>按积分排序</span>
            </div>
          )}
        </div>
      </div>

      {/* 总排行榜使用列表视图，其他模式使用段位视图 */}
      {category === "overall" ? (
        <div className="space-y-2 transition-all duration-300 bg-[#1e2126]/50 backdrop-blur-sm p-4 rounded-lg shadow-md">
          <div className="hidden md:grid grid-cols-12 gap-4 px-4 py-2 text-gray-400 text-sm font-medium border-b border-gray-800 mb-3">
            <div className="col-span-1 flex items-center gap-2">
              <Trophy className="w-4 h-4 text-yellow-500 opacity-80" />
              <span>排名</span>
            </div>
            <div className="col-span-5 md:col-span-4">选手</div>
            <div className="col-span-2 md:col-span-3">地区</div>
            <div className="col-span-4">等级</div>
          </div>
          <div className="space-y-2 md:space-y-3">
            {displayPlayers.map((player, index) => (
              <div
                key={player.id}
                ref={index === displayPlayers.length - 1 ? lastPlayerElementRef : undefined}
                className="transform transition-transform duration-300 hover:translate-x-1"
              >
                <PlayerRow player={player} category={category} />
              </div>
            ))}
            
            {/* 加载更多指示器 */}
            {loadingMore && (
              <div className="text-center py-4">
                <div className="inline-block w-6 h-6 border-2 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
                <p className="text-gray-400 text-sm mt-2">加载更多...</p>
              </div>
            )}
            
            {/* 没有更多数据提示 */}
            {!hasMore && displayPlayers.length > 0 && (
              <div className="text-center py-4 text-gray-500 text-sm bg-gray-800/30 rounded-lg mt-3">
                <Trophy className="h-5 w-5 text-yellow-500/70 mx-auto mb-2" />
                已显示全部 {allPlayers.length} 名玩家
              </div>
            )}
            
            {/* 空数据提示 */}
            {displayPlayers.length === 0 && !isLoading && (
              <div className="bg-gray-800/50 rounded-lg p-6 text-center">
                <div className="text-gray-400 mb-2">暂无排名数据</div>
                <div className="text-sm text-gray-500">请稍后再试</div>
              </div>
            )}
          </div>
        </div>
      ) : (
        <TierView players={allPlayers} category={category} />
      )}
    </div>
  );
}

// 获取分类名称
function getCategoryName(category: string): string {
  switch(category) {
    case "overall": return "总体";
    case "combat": return "剑术";
    case "crystal": return "水晶";
    case "heart": return "UHC";
    case "potion": return "药水";
    case "discord": return "合金pot";
    case "circle": return "SMP";
    default: return category;
  }
}
